package com.hziee.graduate.ticket.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hziee.graduate.ticket.dao.RoomDao;
import com.hziee.graduate.ticket.dao.RoomRecordDao;
import com.hziee.graduate.ticket.dao.ScheduleDao;
import com.hziee.graduate.ticket.dao.UserDao;
import com.hziee.graduate.ticket.dto.R;
import com.hziee.graduate.ticket.entity.Room;
import com.hziee.graduate.ticket.entity.RoomRecord;
import com.hziee.graduate.ticket.entity.Schedule;
import com.hziee.graduate.ticket.entity.User;
import com.hziee.graduate.ticket.service.RoomRecordService;
import com.hziee.graduate.ticket.utils.BeanConvertUtil;
import com.hziee.graduate.ticket.vo.RoomRecordVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("roomRecordService")
public class RoomRecordServiceImpl extends ServiceImpl<RoomRecordDao, RoomRecord> implements RoomRecordService {
    @Resource
    private RoomDao roomDao;

    @Resource
    private RoomRecordDao roomRecordDao;

    @Resource
    private UserDao userDao;

    @Resource
    private ScheduleDao scheduleDao;

    @Override
    public R<RoomRecordVO> addARoomRecord(Map<String, Object> map) {
        Long cinemaId = Long.parseLong(map.get("cinemaId").toString());
        Long roomId = Long.parseLong(map.get("roomId").toString());
        Long createPerson = Long.parseLong(map.get("createPerson").toString());
        String mem = map.get("mem").toString();
        // 添加一条记录
        RoomRecord roomRecord = new RoomRecord();
        roomRecord.setRoomId(roomId);
        roomRecord.setCreatePerson(createPerson);
        roomRecord.setMem(mem);
        roomRecord.setCreateTime(LocalDateTime.now());
        roomRecord.setOptType(0);
        roomRecord.setState(0);
        roomRecord.setDone(0);
        roomRecord.setCinemaId(cinemaId);
        // 统一七天后可以就进行解封解封
        roomRecord.setRelieveTime(LocalDateTime.now().plusDays(7));
        roomRecordDao.insert(roomRecord);
        // 将影院的状态置为关闭
        Room roomInfo = roomDao.selectById(roomId);
        roomInfo.setRoomOpen(0);
        roomDao.update(roomInfo,new UpdateWrapper<Room>().eq("room_id",roomId));
        // 返回需要的结果
        RoomRecordVO roomRecordVO = new RoomRecordVO();
        BeanUtils.copyProperties(roomRecord,roomRecordVO);
        RoomRecordVO res = populateRoomRecordVO(
                createPerson,
                roomId,
                roomRecordVO
        );
        return R.success(res);
    }

    @Override
    @Transactional
    public R<List<RoomRecordVO>> getAllRoomRecordOrderByTime(Long cinemaId) {
        DecimalFormat decimalFormat = new DecimalFormat("00.#");
        // 按照时间倒叙排，从今天开始往前推一个月的数据
        List<RoomRecord> roomRecord =  roomRecordDao.getAllRoomRecordOrderByTime(cinemaId);
        // 判断当前记录是否可操作
        roomRecord.forEach(item -> {
            // 获取截止日期前的最后一次排班时间
            Schedule latestSchedule = scheduleDao.getLatestScheduleBeforeDate(item.getRelieveTime().toLocalDate().toString(),item.getRoomId());
            // 如果现在时间大于最后一次排班时间，说明可编辑, 否则该记录不可编辑
            if(latestSchedule!=null) {
                Date date = null;     //详细日期
                try {
                    date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                            .parse(
                                    latestSchedule.getDate() + " "
                                            + decimalFormat.format(latestSchedule.getEnd() / 60) + ":"
                                            + decimalFormat.format(latestSchedule.getEnd() % 60) + ":00"
                            );
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (new Date().after(date)) {
                    // 更新状态为可编辑
                    item.setState(1);
                    roomRecordDao
                            .update(item,new UpdateWrapper<RoomRecord>()
                                    .eq("room_record_id",item.getRoomRecordId()));
                }
            }else{
                // 该影院没有任何一场排班，更新状态为可编辑
                item.setState(1);
                roomRecordDao
                        .update(item,new UpdateWrapper<RoomRecord>()
                                .eq("room_record_id",item.getRoomRecordId()));
            }
        });
        // 填充数据
        List<RoomRecordVO> roomRecordVO = BeanConvertUtil.converList(roomRecord,RoomRecordVO.class);
        for (int i = 0; i < roomRecord.size(); i++) {
            populateRoomRecordVO(roomRecord.get(i).getCreatePerson(),roomRecord.get(i).getRoomId(),roomRecordVO.get(i));
        }

        return R.success(roomRecordVO);
    }

    private RoomRecordVO populateRoomRecordVO(Long userId, Long roomId, RoomRecordVO roomRecordVO) {
        // 查询用户信息
        User createPerson = userDao.selectById(userId);
        roomRecordVO.setCreatePersonName(createPerson.getNick());
        // 查询房间信息
        Room roomInfo = roomDao.selectById(roomId);
        roomRecordVO.setRoomInfo(roomInfo);
        return roomRecordVO;
    }
}

